﻿using System;
using BankInvest.InstrumentEditor.Domain.Entities;
using NHibernate;

namespace BankInvest.InstrumentEditor.Domain.Repositories
{
    public class InstrumentRepository : IInstrumentRepository
    {
        private readonly ISession _session;

        public InstrumentRepository(ISession session)
        {
            _session = session;
        }

        public void AddOrMerge(Instrument instrument)
        {
            var instrumentFromSession = _session.Get<Instrument>(instrument.Id);

            if (instrumentFromSession == null)
            {
                _session.Save(instrument);
            }
            else
            {
                instrumentFromSession.Id = instrument.Id;
                instrumentFromSession.Name = instrument.Name;
                instrumentFromSession.IsActive = instrument.IsActive;
                instrumentFromSession.Type = instrument.Type;

                _session.Update(instrumentFromSession);
            }
        }

        public Instrument Get(string id)
        {
            return _session.Get<Instrument>(id);
        }
    }
}